//
//  KKGoodsEditView.m
//  Butler
//
//  Created by liaozhenming on 16/6/22.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

#import "KKGoodsEditView.h"

#import "CategoryCollectionViewCell.h"

@interface KKGoodsEditView()<UITextFieldDelegate>

@property (nonatomic, strong) UICollectionView *categoryCollectionView;
@property (nonatomic, strong) UIAlertController *categoryEditAlert;

@property (nonatomic, strong) UITextField *nameField;
@property (nonatomic, strong) UITextField *priceField;

@property (nonatomic, strong) NSMutableArray *arr_categoryItems;

@property (nonatomic, strong) KKCategoryItem *selectedItem;

@end

@implementation KKGoodsEditView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        UIView *contentView = [self contentView];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth(contentView.bounds), 44)];
        titleLabel.backgroundColor = [UIColor kk_colorWithHexString: @"71d47c"];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.text = @"新增商品";
        [contentView addSubview: titleLabel];
        
        UIImageView *headerImageView = [[UIImageView alloc] initWithFrame: CGRectMake(20, 64, 120, 120)];
        headerImageView.backgroundColor = [UIColor yellowColor];
        [contentView addSubview: headerImageView];
        
        CGFloat pointY = 80;
        {
            UILabel *nameTipsLabel = [[UILabel alloc] initWithFrame: CGRectMake(150, pointY, 100, 20)];
            nameTipsLabel.backgroundColor = [UIColor clearColor];
            nameTipsLabel.text = @"商品名称:";
            nameTipsLabel.textColor = [UIColor kk_colorWithHexString: @"555555"];
            [contentView addSubview: nameTipsLabel];
            
            UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(180, pointY + 25, CGRectGetWidth(contentView.bounds) - 200, 26)];
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.delegate = self;
            [contentView addSubview: textField];
            _nameField = textField;
            pointY += 60;
        }
        
        {
            UILabel *nameTipsLabel = [[UILabel alloc] initWithFrame: CGRectMake(150, pointY, 100, 20)];
            nameTipsLabel.backgroundColor = [UIColor clearColor];
            nameTipsLabel.text = @"商品价格:";
            nameTipsLabel.textColor = [UIColor kk_colorWithHexString: @"555555"];
            [contentView addSubview: nameTipsLabel];
            
            UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(180, pointY + 25, CGRectGetWidth(contentView.bounds) - 200, 26)];
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.delegate = self;
            textField.keyboardType = UIKeyboardTypeNumberPad;
            [contentView addSubview: textField];
            _priceField = textField;
            pointY += 60;
        }
        
        {
            UILabel *nameTipsLabel = [[UILabel alloc] initWithFrame: CGRectMake(150, pointY, 100, 20)];
            nameTipsLabel.backgroundColor = [UIColor clearColor];
            nameTipsLabel.text = @"商品分类:";
            nameTipsLabel.textColor = [UIColor kk_colorWithHexString: @"555555"];
            [contentView addSubview: nameTipsLabel];
            
            UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
            _categoryCollectionView = [[UICollectionView alloc] initWithFrame: CGRectMake(180, pointY + 25, CGRectGetWidth(contentView.bounds) - 200, CGRectGetHeight(contentView.bounds) - pointY - 100) collectionViewLayout: flowLayout];
            _categoryCollectionView.backgroundColor = [UIColor kk_colorWithHexString: @"f0f0f0"];
            _categoryCollectionView.dataSource = self;
            _categoryCollectionView.delegate = self;
            [_categoryCollectionView registerNib: [UINib nibWithNibName: @"CategoryCollectionViewCell" bundle: nil] forCellWithReuseIdentifier: NSStringFromClass([CategoryCollectionViewCell class])];
            
            [contentView addSubview: _categoryCollectionView];
        }

        UIButton *cancelButton = [UIButton buttonWithType: UIButtonTypeSystem];
        cancelButton.frame = CGRectMake(30, CGRectGetHeight(contentView.bounds) - 50, 120, 34);
        cancelButton.backgroundColor = [UIColor kk_colorWithHexString: @"71d47c"];
        [cancelButton setTitle: @"取消" forState: UIControlStateNormal];
        [cancelButton setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
        [cancelButton addTarget: self action: @selector(action_cancel:) forControlEvents: UIControlEventTouchUpInside];
        [cancelButton kk_cornerRadius: 3.0];
        [contentView addSubview: cancelButton];
        
        UIButton *sureButton = [UIButton buttonWithType: UIButtonTypeSystem];
        sureButton.frame = CGRectMake(CGRectGetWidth(contentView.bounds) - 150, CGRectGetHeight(contentView.bounds) - 50, 120, 34);
        sureButton.backgroundColor = [UIColor kk_colorWithHexString: @"71d47c"];
        [sureButton setTitle: @"确定" forState: UIControlStateNormal];
        [sureButton setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
        [sureButton addTarget: self action: @selector(action_save:) forControlEvents: UIControlEventTouchUpInside];
        [sureButton kk_cornerRadius: 3.0];
        [contentView addSubview: sureButton];
    }
    return self;
}

#pragma mark - Private methods

- (void)kk_show {
    [super kk_show];
    
    _arr_categoryItems = [NSMutableArray arrayWithArray: [[KKButlerDataManager kk_manager] arr_categoryItems]];
}

#pragma mark - Action methods

- (void)action_cancel:(UIBarButtonItem*)item {
    
    [self kk_close];
}

- (void)action_save:(UIBarButtonItem*)item {
    
    if (_selectedItem == nil) {
        return;
    }
    
    NSString *name = _nameField.text;
    NSString *price = _priceField.text;
    
    if (name.length == 0) {
        return;
    }
    if (price.length == 0) {
        return;
    }
    
    [[KKDataBaseManager defaultManager] insertRecordIntoTableName: KKDataBase_TableName_GoodsInfo withRecords: @{@"name":name,@"price":price,@"categoryId":_selectedItem.kk_id} finishHandle:^(id object, BOOL successful) {
        
        if (successful && object != nil) {
            //  有新数据，需要更新
            [[NSNotificationCenter defaultCenter] postNotificationName: KKButlerDataManagerUpdateNotificationNameGoods object: nil];
        }
    }];
    
    [self kk_close];
}

#pragma mark - UICollectionView methods

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 1+_arr_categoryItems.count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CategoryCollectionViewCell *itemCell = [collectionView dequeueReusableCellWithReuseIdentifier:  NSStringFromClass([CategoryCollectionViewCell class]) forIndexPath: indexPath];
    
    if (indexPath.row == 0) {
        itemCell.lab_categoryName.text = @"+";
        itemCell.backgroundColor = [UIColor orangeColor];
        return itemCell;
    }
    else {
        
        itemCell.backgroundColor = [UIColor orangeColor];
        KKCategoryItem *item = [self.arr_categoryItems objectAtIndex: indexPath.row - 1];
        itemCell.lab_categoryName.text = item.kk_name;
        return itemCell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return CGSizeMake(60, 30);
    }
    
    return CGSizeMake(100, 30);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        if (_categoryEditAlert == nil) {
            _categoryEditAlert = [UIAlertController alertControllerWithTitle: @"新增分类" message: nil preferredStyle: UIAlertControllerStyleAlert];
            [_categoryEditAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            }];
            
            __weak typeof(_categoryEditAlert) weakAlert = _categoryEditAlert;
            __weak typeof(self) weakSelf = self;
            UIAlertAction *sureItem = [UIAlertAction actionWithTitle: @"保存" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                UITextField *textfield = [[weakAlert textFields] firstObject];
                [weakSelf private_insertCategoryWithName: textfield.text];
            }];
            UIAlertAction *cancelItem = [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            
            [_categoryEditAlert addAction: sureItem];
            [_categoryEditAlert addAction: cancelItem];
        }
        
        UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        [rootViewController presentViewController: _categoryEditAlert animated: YES completion: nil];
    }
    else {
        KKCategoryItem *item = [self.arr_categoryItems objectAtIndex: indexPath.row - 1];
        _selectedItem = item;
    }
}

#pragma mark - Private methods

- (void)private_insertCategoryWithName:(NSString*)name {
    
    if (name.length > 0) {
        __weak typeof(_arr_categoryItems) weakItems = _arr_categoryItems;
        __weak typeof(_categoryCollectionView) weakCollectionView = _categoryCollectionView;
        [[KKDataBaseManager defaultManager] insertRecordIntoTableName: KKDataBase_TableName_GoodsCategory withRecords: @{@"name":name} finishHandle:^(id object, BOOL successful) {
            if (successful && object != nil) {
                KKCategoryItem *item = [KKCategoryItem new];
                item.kk_id = object;
                item.kk_name = name;
                [weakItems addObject: item];
                [weakCollectionView reloadData];
            }
        }];
    }
}

@end
